using System;
using System.Collections.Generic;
using System.Text;
using PSLibrary = Microsoft.Office.Project.Server.Library;
using System.Web.Services.Protocols;
using System.Net;
using System.Globalization;
using Microsoft.Office.Project.EPMSync.Config.Library;

namespace Microsoft.Office.Project.EPMSync.Service
{
    /// <summary>
    /// Holds a collection of custom fields so the EPMSync doens't need to keep going back to Project Server.
    /// </summary>
    class CustomFieldCollection
    {
        private Dictionary<Guid, byte> _projectCustomFieldList;
        private Dictionary<Guid, Guid> _customFieldsWithLookupTables;
        private Tracing _tracing;
        CustomFieldsWS.CustomFields _customFieldsWebSvc;
        private SyncConfig _config;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="tracing">Pointer to the active tracing component.</param>
        /// <param name="customFieldsWebSvc">Connection to custom fields web service.</param>
        /// <param name="config">Pointer to the active configuration.</param>
        public CustomFieldCollection(Tracing tracing, CustomFieldsWS.CustomFields customFieldsWebSvc, SyncConfig config)
        {
            _tracing = tracing;
            _customFieldsWebSvc = customFieldsWebSvc;
            _config = config;
        }


        /// <summary>
        /// Makes sure the list of custom fields has been read.
        /// </summary>
        /// <returns>True if the custom field list has been intialized.</returns>
        public bool Initialize()
        {
            if (_projectCustomFieldList != null)
            {
                _projectCustomFieldList.Clear();
                _customFieldsWithLookupTables.Clear();
            }
            else
            {
                _projectCustomFieldList = new Dictionary<Guid, byte>();
                _customFieldsWithLookupTables = new Dictionary<Guid, Guid>();
            }

            try
            {
                CustomFieldsWS.CustomFieldDataSet cfDataSet = _customFieldsWebSvc.ReadCustomFieldsByEntity(new Guid(PSLibrary.EntityCollection.Entities.ProjectEntity.UniqueId));

                foreach (CustomFieldsWS.CustomFieldDataSet.CustomFieldsRow cfr in cfDataSet.CustomFields)
                {
                    _projectCustomFieldList.Add(cfr.MD_PROP_UID, cfr.MD_PROP_TYPE_ENUM);
                    if (!cfr.IsMD_LOOKUP_TABLE_UIDNull())
                        _customFieldsWithLookupTables.Add(cfr.MD_PROP_UID, cfr.MD_LOOKUP_TABLE_UID);
                }

            }
            catch (SoapException ex)
            {
                _tracing.WriteTrace(_tracing.MainSwitch.TraceError, String.Format(CultureInfo.InvariantCulture, "A SOAP exception occurred during ReadCustomFieldsByEntity: \r\n{0}", PSError.FormattedMessage(ex)));
                return false;
            }
            catch (WebException ex)
            {
                _tracing.WriteTrace(_tracing.MainSwitch.TraceError, String.Format(CultureInfo.InvariantCulture, "An WebException occurred during ReadCustomFieldsByEntity: \r\n{0}", ex.Message));
                return false;
            }
            catch (Exception ex)
            {
                _tracing.WriteTrace(_tracing.MainSwitch.TraceError, String.Format(CultureInfo.InvariantCulture, "An exception occurred during ReadCustomFieldsByEntity: \r\n{0}", ex.Message));
                return false;
            }

            return true;

        }

        /// <summary>
        /// Iterates through the custom fields mapped in the config file and verifies they are valid custom fields.
        /// </summary>
        /// <returns>Returns true if all the custom fields are valid.</returns>
        public bool MappedCustomFieldsExist()
        {
            foreach (FieldMapping fm in _config.FieldMappings)
            {
                if (fm.PSField.CustomFieldUid != Guid.Empty)
                {
                    if (_projectCustomFieldList[fm.PSField.CustomFieldUid] == 0)
                        return false;
                }
                else if (fm.PSField.BuiltInName.Length > 0)
                {
                    if (!BuiltInFields.IsFieldValid(fm.PSField.BuiltInName))
                        return false;
                }
                else
                    return false;
            }
            return true;
        }

        /// <summary>
        /// Searches if the specified custom field has a lookup table associated with it.
        /// </summary>
        /// <param name="customFieldUid">The Guid for the specified custom field.</param>
        /// <returns>Return true if the custom field has a lookup table associated with it.</returns>
        public bool CustomFieldHasLookupTable(Guid customFieldUid)
        {
            if (_customFieldsWithLookupTables != null)
            {
                foreach (KeyValuePair<Guid, Guid> kvp in _customFieldsWithLookupTables)
                {
                    //if (kvp.Value == CustomFieldID)
                    if (kvp.Key == customFieldUid)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// Find the type (Project, Task, Resource, Assignment) of the specified custom field.
        /// </summary>
        /// <param name="customFieldID">The Guid for the specified custom field.</param>
        /// <returns>Returns the type of the custom field.</returns>
        public byte getCustomFieldType(Guid customFieldID)
        {
            bool tryAgain = true;
            int tryCount = 1;
            do
            {
                try
                {
                    return _projectCustomFieldList[customFieldID];
                }
                catch (KeyNotFoundException)
                {
                    if (tryCount++ == 2)
                        tryAgain = false;
                    else
                    {
                        // Reread the project custom field list from Project Server to check for changes.
                        Initialize();
                    }
                }
            }
            while (tryAgain);

            // A valid project custom field was not found in the list
            return 0;

        }

    }
}
